'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 市场
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var configUtil = require('../../../util/configUtil');
var PlayerManager = require('../../../libs/playerManager');
var marketConf = require('../../../config/marketConf');
var dataApi = require('../../../libs/dataApi');
var rewardService = require('../../../services/rewardService');
var taskService = require('../../../services/taskService');
var genRewardService = require('../../../services/genRewardService');
var costType = require('../../../consts/costType.js');
var buildType = require('../../../consts/buildType.js');
var roleService = require('../../../services/roleService.js');
var constantUtil = require('../../../util/constantUtil');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 查询市场物品列表
 * @param  {[type]} msg     [description]
 * @param  {[type]} session [description]
 * @param  {[type]} next    [description]
 * @return {[type]}     [description]
 */
Handler.prototype.list = function (msg, session, next) {
    var role_id = session.uid;
    var player_manager = new PlayerManager(role_id);
    var result = {
        market_list: [],
        free_times: 0,
        refresh_times: 0,
        next_refresh_tm: 0
    };
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['market', 'build', 'role', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var market_model = player_manager.market;
                var build_model = player_manager.build;
                var market_build = build_model.getBuildByType(buildType.MARKET);
                var changed = market_model.checkDataLvl(market_build.getLv());

                // 给物品列表附加其它属性
                var market_list = [];
                _.each(market_model.market_list, function (market_item) {
                    market_list.push({
                        market_pos: market_item.market_pos,
                        market_id: market_item.market_id,
                        discount: market_item.discount
                    });
                });

                // 返回最终值
                result.market_list = market_list;
                result.free_times = market_model.free_times;
                result.refresh_times = market_model.refresh_times;
                result.next_refresh_tm = 2147483647;
                result.market_data_lv = market_build.getLv();

                if (!!changed) {
                    player_manager.save(cb);
                } else {
                    cb();
                }
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: result
            });
        }
    );
};

/**
 * 刷新市场物品
 * @param  {[type]} msg     [description]
 * @param  {[type]} session [description]
 * @param  {[type]} next    [description]
 * @return {[type]}     [description]
 */
Handler.prototype.refresh = function (msg, session, next) {
    var role_id = session.uid;
    var player_manager = new PlayerManager(role_id);
    var result = {
        market_list: [],
        free_times: 0,
        refresh_times: 0,
        next_refresh_tm: 0
    };
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['market', 'build', 'role', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var market_model = player_manager.market;

                if (market_model.free_times > 0) {
                    market_model.free_times--;
                } else {
                    // 递增扣减钻石
                    var diamond_num = _getSubDiamond(market_model.refresh_times + 1);
                    if (!roleService.subDiamond(player_manager, moduleType.MDL_MARKET, operationType.OPR_MARKET_REFRESH, diamond_num)) {
                        return next(null, {
                            code: Code.USER_DIAMOND_NOT_ENOUGH
                        });
                    }

                    market_model.refresh_times++;
                }

                // 生成新的物品列表
                market_model.randMarketList();

                // 给物品列表附加其它属性
                var market_list = [];
                _.each(market_model.market_list, function (market_item) {
                    market_list.push({
                        market_pos: market_item.market_pos,
                        market_id: market_item.market_id,
                        discount: market_item.discount
                    });
                });

                // 返回最终值
                result.market_list = market_list;
                result.free_times = market_model.free_times;
                result.refresh_times = market_model.refresh_times;
                result.next_refresh_tm = market_model.next_refresh_tm;
                taskService.addRefreshMarket(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: result
            });
        }
    );
};

/**
 * 购买市场物品
 * @param  {[type]} msg     [description]
 * @param  {[type]} session [description]
 * @param  {[type]} next    [description]
 * @return {[type]}     [description]
 */
Handler.prototype.buy = function (msg, session, next) {
    var role_id = session.uid;
    var market_pos = msg.market_pos;
    var new_market_item = {};
    /*
    扣减相应资源
    给玩家增加物品
    刷新单个物品
    */
    var player_manager = new PlayerManager(role_id);
    var market_list = null;
    var free_times = 0;
    var refresh_times = 0;
    var next_refresh_tm = 0;
    var reward_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['market', 'build', 'role', 'bag', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var market_model = player_manager.market;
                var market_item = market_model.market_list[market_pos];
                if (!market_item) {
                    return next(null, {
                        code: Code.MARKET_ERROR_MARKET_POS
                    });
                }
                var mkt_item_info = marketConf.findByID(market_model.market_data_lv, market_item.market_id);
                if (!market_item) {
                    return next(null, {
                        code: Code.MARKET_ERROR_MARKET_ID
                    });
                }

                // 扣减资源
                var cost_num = Math.floor(mkt_item_info.cost_num * market_item.discount / 100);
                var err_code = _subRoleResource(player_manager, market_item.market_id, mkt_item_info.cost_type, cost_num);
                if (err_code != Code.OK) {
                    return next(null, {
                        code: err_code
                    });
                }

                // 奖励物品
                var reward = genRewardService.generateReward(mkt_item_info);
                rewardService.addRewardToRole(player_manager, reward, moduleType.MDL_MARKET, operationType.OPR_MARKET_BUY);
                reward_list.push(reward);

                // 刷新单个物品
                var rand_item = market_model.randMarketPos(market_pos);
                new_market_item = {
                    market_pos: rand_item.market_pos,
                    market_id: rand_item.market_id,
                    discount: rand_item.discount
                };
                taskService.addBuyMarket(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    new_market_item: new_market_item,
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 获取刷新市场所城消耗钻石
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _getSubDiamond = function (refresh_times) {
    var refresh_conf = dataApi.market_refresh.findById(refresh_times);
    if (!refresh_conf) {
        return 500;
    }

    return refresh_conf.cost;
};

/**
 * 扣减玩家资源
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _subRoleResource = function (player_manager, market_id, cost_type, const_num) {
    switch (cost_type) {
    case costType.GOLD:
        {
            if (!roleService.subGold(player_manager, moduleType.MDL_MARKET, operationType.OPR_MARKET_BUY, const_num, market_id)) {
                return Code.USER_GOLD_NOT_ENOUGH;
            }
            break;
        }
    case costType.DIAMOND:
        {
            if (!roleService.subDiamond(player_manager, moduleType.MDL_MARKET, operationType.OPR_MARKET_BUY, const_num, market_id)) {
                return Code.USER_DIAMOND_NOT_ENOUGH;
            }
            break;
        }
    case costType.DRAGON_GOLD:
        {
            if (!roleService.subDragonGold(player_manager, moduleType.MDL_MARKET, operationType.OPR_MARKET_BUY, const_num, market_id)) {
                return Code.USER_DRAGON_NOT_ENOUGH;
            }
            break;
        }
    case costType.FOOD:
        {
            if (!roleService.subFood(player_manager, moduleType.MDL_MARKET, operationType.OPR_MARKET_BUY, const_num, market_id)) {
                return Code.USER_FOOD_NOT_ENOUGH;
            }
            break;
        }
    default:
        {
            console.error('cost type is wrong:' + cost_type);
            return Code.UESR_INVALID_COST_TYPE;
        }
    }
    return Code.OK;
};
